package com.example.myprogram;

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;


public class AttachTest {

    public static void main(String[] args) throws IOException, AttachNotSupportedException, InterruptedException {
        String pidByPort = getPIDByPort("8888");
        System.out.println(pidByPort);
        attach(pidByPort);
    }

    public static void attach(String PID) throws IOException, AttachNotSupportedException {
        //  表示目标进程的PID
        VirtualMachine virtualMachine = VirtualMachine.attach(PID);
        // 指定Java Agent的jar包路径
        try {
            virtualMachine.loadAgent("F:\\javacode\\InstrumentationCode\\java-agenttest\\target\\java-agenttest-1.0-SNAPSHOT-jar-with-dependencies.jar", "sizengli");
        } catch (AgentLoadException e) {
            e.printStackTrace();
        } catch (AgentInitializationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            virtualMachine.detach();
        }
    }

    public static String getPIDByPort(String port) throws IOException, InterruptedException {
        String result = null;
        ArrayList<ArrayList<String> > list = new ArrayList<>();
        Process process = Runtime.getRuntime().exec("netstat -aon");
        InputStream inputStream = process.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer();
        String message;
        // 读取每一行
        while((message = bufferedReader.readLine()) != null){
            ArrayList<String> li = new ArrayList<>();
            String[] s = message.trim().split(" ");
            for(int i=0;i<s.length;i++){
                if(s[i].length() == 0){
                    continue;
                }
                li.add(s[i]);
            }
            list.add(li);
        }

        for(int i=0;i<list.size();i++){
            ArrayList<String> list1 = list.get(i);
            if(list1.size() < 2){
                continue;
            }
            String s = list1.get(1);
            String[] split = s.split(":");
            if(split[split.length-1].equals(port)){
                result = list1.get(list1.size()-1);
            }
        }
        return result;
    }
}
